package com.sgb.kjwl.view.widget.transport

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.TextUtils
import android.text.style.ForegroundColorSpan
import android.util.Log
import android.view.LayoutInflater
import android.widget.FrameLayout
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.GridLayoutManager
import com.sgb.kjwl.R
import com.sgb.kjwl.api.NewAPIManager
import com.sgb.kjwl.databinding.ViewLogisticsOwnerWorkbenchBinding
import com.sgb.kjwl.model.entity.transport.OwnerWorkbenchEntity
import com.sgb.kjwl.model.entity.transport.SingleItemEntity
import com.sgb.kjwl.utils.NumberUtil
import com.swgk.core.event.EventConstant
import com.sgb.kjwl.view.event.LogisticsEvent
import com.sgb.kjwl.view.ui.activity.self.logistics.CargoManageActivity
import com.sgb.kjwl.view.ui.activity.self.logistics.PublishCargoActivity
import com.sgb.kjwl.view.ui.activity.self.offer.TruckRegisterActivity
import com.sgb.kjwl.view.ui.activity.transport.CarriageDetailActivity
import com.sgb.kjwl.view.ui.activity.transport.driver.goods.FreightPrjDetailActivity
import com.sgb.kjwl.view.ui.activity.transport.driver.goods.GeneralPrjDetailActivity
import com.sgb.kjwl.view.ui.activity.transport.owner.FreightCarTransportationActivity
import com.sgb.kjwl.view.ui.activity.transport.owner.TransportOrderOwnerActivity
import com.swgk.core.base.api.ICallBack
import com.swgk.core.base.model.entity.BaseEntity
import com.swgk.core.util.TimeUtils
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * @author: 杨畔
 * @date: 4/5/21 10:14 AM
 * @Description: 货主工作台
 */
class LogisticsOwnerWorkbenchView(context: Context) : FrameLayout(context) {
    private var mContext = context
    private var mBinding: ViewLogisticsOwnerWorkbenchBinding = DataBindingUtil.inflate(
        LayoutInflater.from(mContext),
        R.layout.view_logistics_owner_workbench,
        null,
        false
    )

    //菜单列表
    private val mMenus = mutableListOf<SingleItemEntity>()
    private var mAdapter: LogisticsWorkbenchMenuAdapter? = null

    //货源数据
    private var mEntity: OwnerWorkbenchEntity.LatelyGoodsSourceBean? = null

    init {
        addView(mBinding.root)
        initRecycler()
        initEvent()
    }

    private fun initRecycler() {
        mMenus.add(SingleItemEntity(0, R.mipmap.ic_owner_workbench_notice, "找车公示", true, 99))
        mMenus.add(SingleItemEntity(0, R.mipmap.ic_owner_workbench_find_car, "竞价找车", true, 99))
        mMenus.add(SingleItemEntity(0, R.mipmap.ic_owner_workbench_carriage, "货车承运", true, 99))
        mMenus.add(SingleItemEntity(0, R.mipmap.ic_owner_workbench_offer, "竞价报名", true, 99))
        mMenus.add(SingleItemEntity(0, R.mipmap.ic_owner_workbench_order, "订单信息", true, 99))
        mAdapter = LogisticsWorkbenchMenuAdapter(mMenus)
        mBinding.rvLwBtn.layoutManager = GridLayoutManager(mContext, 5)
        mAdapter?.bindToRecyclerView(mBinding.rvLwBtn)
    }

    private fun initEvent() {
        mAdapter?.setOnItemClickListener { _, _, position ->
            val entity = mMenus[position]
            when (entity.leftString) {
                "找车公示" -> {
                    //点击后跳转用户中心 - 货主 - 普通货源管理页。
                    CargoManageActivity.start(context, true)
                }
                "竞价找车" -> {
                    //点击后跳转用户中心 - 货主 - 竞价货源管理页。
                    CargoManageActivity.start(context, false)
                }
                "货车承运" -> {
                    //设置已读
                    mMenus[0].number = 0
                    mAdapter?.notifyDataSetChanged()
                    //点击后跳转用户中心 - 货主 - 货车承运页
                    FreightCarTransportationActivity.start(context, true)
                }
                "竞价报名" -> {
                    //点击后跳转用户中心 - 货主 - 货车报名页。
                    TruckRegisterActivity.start(context, true)
                }
                "订单信息" -> {
                    //点击打开货主订单列表页。
                    TransportOrderOwnerActivity.start(context)
                }
            }
        }
        mBinding.tvLwDetail.setOnClickListener {
            //todo 查看详情
            mEntity?.apply {
                if (pattern != null) {
                    if (pattern == 1) {
                        FreightPrjDetailActivity.start(mContext, sourceNo, false, true)
                    } else {
                        GeneralPrjDetailActivity.start(mContext, sourceNo, pattern, true)
                    }
                }
            }
        }
        mBinding.tvLwRelease.setOnClickListener {
//            if (UserOperating.getInstance().isNotOpenFundAccount(mContext, PermissionCheckUtil.KEY_HUOYUANGUANLI)
//            ) {
//                return@setOnClickListener
//            }
            //发布普通货源
            PublishCargoActivity.start(mContext)
        }
        mBinding.tvLwMore.setOnClickListener {
            //todo 更多消息，2.0.3版本隐藏
        }
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        Log.e("workbench", "onAttachedToWindow")
        refreshData()
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        Log.e("workbench", "onDetachedFromWindow")
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun refresh(event: LogisticsEvent) {
        if (event.messageTag == EventConstant.EVENT_REFRESH_WORKBENCH) {
            refreshData()
        }
    }

    private fun refreshData() {
        NewAPIManager.getInstance().logisticsAPI.ownerWorkbench()
            .enqueue(object : ICallBack<BaseEntity<OwnerWorkbenchEntity>>() {
                override fun onSuccess(data: BaseEntity<OwnerWorkbenchEntity>?) {
                    syncData(data?.data)
                }
            })
    }

    @SuppressLint("SetTextI18n")
    private fun syncData(data: OwnerWorkbenchEntity?) {
        if (data == null) {
            mEntity = null
            mBinding.flLwRelease.visibility = VISIBLE
            mBinding.clLwMessage.visibility = GONE
            mBinding.tvLwDetail.visibility = GONE
            return
        }

        if (data.latelyGoodsSource == null) {
            mEntity = null
            mBinding.flLwRelease.visibility = VISIBLE
            mBinding.tvLwDetail.visibility = GONE
        } else {
            mEntity = data.latelyGoodsSource
            mBinding.flLwRelease.visibility = GONE
            mBinding.tvLwDetail.visibility = VISIBLE
            //最新消息数量
            mMenus[2].number = data.carrierCount
            mAdapter?.notifyDataSetChanged()
            //货源信息
            data.latelyGoodsSource?.apply {
                if (pattern != null && pattern == 1) {
                    mBinding.tvLwGoodsType.text = "竞价货源"
                    mBinding.tvLwGoodsType.visibility = VISIBLE
                } else {
                    mBinding.tvLwGoodsType.visibility = GONE
                }
                mBinding.tvLwLoadPlace.text = "$provinceName $cityName"
                mBinding.tvLwUnloadPlace.text = "$destProvinceName $destCityName"
                mBinding.tvLwGoods.text = "$goodsLastTypeName  $weight  $volume"
                if (freightType == null || freightType == 0) {
                    mBinding.tvLwFreight.text = if (freight != null) {
                        "${NumberUtil.trim0(freight)}元"
                    } else {
                        ""
                    }
                } else {
                    mBinding.tvLwFreight.text = "电议"
                }
                if (pattern != null && pattern == 1) {
                    mBinding.tvLwDate.text = "$shipmentTimeStr"
                } else {
                    mBinding.tvLwDate.text = "$shipmentTimeStr"
                }
            }
        }

        mBinding.clLwMessage.visibility = GONE
        data.messageList?.takeIf {
            mBinding.clLwMessage.visibility = if (it.size == 0) GONE else VISIBLE
            it.size > 0
        }?.let {
            it[0]
        }?.apply {
            //消息
            mBinding.clLwMessage.visibility = if (TextUtils.isEmpty(content)) GONE else VISIBLE
            mBinding.tvLwMsgPlace.text =
                "$provinceName-$cityName-$districtName → $destProvinceName-$destCityName-$destDistrictName"
            // mBinding.tvLwMsgContent.text = content
            spannableString(content)
            mBinding.tvLwMsgTime.text =
                if (updateTime == null) "" else TimeUtils.getGapCuountTimeFormat(
                    updateTime,
                    System.currentTimeMillis()
                )
            mBinding.tvLwMsgContent.setOnClickListener {
                if (!TextUtils.isEmpty(content)) {
                    CarriageDetailActivity.start(mContext, carrierNo, 1)
                }
            }
        }
    }

    /**
     * 获取可点击的SpannableString
     * @return
     */
    private fun spannableString(string: String?) {
        val textSpannedBuilder1 = SpannableStringBuilder()
        val textSpanned11 = android.text.SpannableString("$string ")
        val textSpanned12 = android.text.SpannableString("查看承运详情 >>")
        val foregroundColor = ForegroundColorSpan(Color.parseColor("#5792FD"))
        textSpanned12.setSpan(
            foregroundColor,
            0,
            textSpanned12.length,
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        mBinding.tvLwMsgContent.text =
            textSpannedBuilder1.append(textSpanned11).append(textSpanned12)
    }
}